package cn.schoolwow.quickapi.util;

import cn.schoolwow.quickapi.module.common.domain.APIEntity;
import cn.schoolwow.quickapi.module.common.domain.APIField;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class QuickAPIUtil {
    /**格式化JSON*/
    public static String formatAndPrettyJSON(String data){
        try {
            if(data.startsWith("{")){
                String format = JSON.toJSONString(JSON.parseObject(data),SerializerFeature.PrettyFormat);
                return format;
            }
            if(data.startsWith("[")){
                String format = JSON.toJSONString(JSON.parseArray(data),SerializerFeature.PrettyFormat);
                return format;
            }
        }catch (Exception e){
        }
        return data;
    }

    public static APIEntity getAPIEntity(Class clazz) {
        if(null!=clazz.getComponentType()){
            clazz = clazz.getComponentType();
        }

        APIEntity apiEntity = new APIEntity();
        apiEntity.clazz = clazz;
        apiEntity.className = clazz.getName();
        apiEntity.simpleName = clazz.getSimpleName();

        List<Field> fieldList = QuickAPIUtil.getAllField(clazz);
        List<APIField> apiFieldList = new ArrayList<>();

        for(Field field:fieldList){
            APIField apiField = new APIField();
            apiField.name = field.getName();
            apiField.type = field.getType().getSimpleName().toLowerCase();
            apiField.classType = field.getType().getName();
            //处理泛型
            Type fieldType = field.getGenericType();
            if (fieldType instanceof ParameterizedType) {
                ParameterizedType pType = (ParameterizedType) fieldType;
                Type genericType = pType.getActualTypeArguments()[0];
                apiField.genericTypeClassName = genericType.getTypeName();
            }

            apiField.field = field;
            apiField.apiEntity = apiEntity;
            apiFieldList.add(apiField);
        }
        apiEntity.apiFieldList = apiFieldList;
        return apiEntity;
    }

    /**
     * 获得该类所有字段(包括父类字段)
     * @param clazz 类
     * */
    public static List<Field> getAllField(Class clazz){
        List<Field> fieldList = new ArrayList<>();
        Class tempClass = clazz;
        while (null != tempClass) {
            Field[] fields = tempClass.getDeclaredFields();
            for (Field field : fields) {
                if (Modifier.isFinal(field.getModifiers()) || Modifier.isStatic(field.getModifiers())) {
                    continue;
                }
                field.setAccessible(true);
                fieldList.add(field);
            }
            tempClass = tempClass.getSuperclass();
        }
        return fieldList;
    }

}
